/* 
 * GrayRabbit Cms基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department：运营部
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.dao.system.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cms.constant.DBInitId;
import org.grayrabbit.cms.dao.system.AdminDao;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.vo.system.AdminBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import org.grayrabbit.dao.impl.GenericHibernateDao;
import org.grayrabbit.dao.util.Page;
import org.grayrabbit.dao.util.QueryCondition;

/**
 * <b>Admin</b> dao implementation 





 * @version 1.0，创建时间：2011-05-16 15:55:12 
 */
@Repository
public class AdminDaoImpl extends GenericHibernateDao<Admin, String>
		implements AdminDao {
	private  static final Logger LOGGER = LoggerFactory.getLogger(AdminDaoImpl.class);
	/**
	 * HQL主体语句
	 */
	public static final String MAIN_HQL = "From Admin as obj";
	/**
	 * HQL中count统计hql片段
	 */
	public static final String COUNT_HQL = "Select Count(obj) ";

	/**
	 * 根据bean组装查询条件
	 * @see AdminDao#assembly(AdminBean)
	 */
	public QueryCondition assembly(AdminBean bean) {
		QueryCondition qc = new QueryCondition(MAIN_HQL);
		transNameQuery(bean,qc);
		return qc;
	}

	/**
	 * 根据bean组装统计查询条件
	 * @see AdminDao#assemblyCount(AdminBean)
	 */
	public QueryCondition assemblyCount(AdminBean bean) {
		QueryCondition qc = new QueryCondition(COUNT_HQL + MAIN_HQL);
		transNameQuery(bean,qc);
		return qc;
	}

	/**
	 * @see AdminDao#count(AdminBean)
	 */
	public int count(AdminBean bean) {
		return ((Long)iterator(assemblyCount(bean)).next()).intValue();
	}

	/**
	 * 根据bean组装查询条件(名称参数)
	 * @see AdminDao#assemblyNameQuery(AdminBean)
	 */
	public QueryCondition assermblyNameQuery(AdminBean bean) {
		QueryCondition qc = new QueryCondition(MAIN_HQL);
		transNameQuery(bean, qc);
		return qc;
	}

	/**
	 * 根据bean组装统计查询条件(名称参数)
	 * @see AdminDao#assemblyNameQueryCount(AdminBean)
	 */
	public QueryCondition assemblyNameQueryCount(AdminBean bean) {
		QueryCondition qc = new QueryCondition(COUNT_HQL + MAIN_HQL);
		transNameQuery(bean,qc);
		return qc;
	}

	/**
	 * 填充分页组件
	 * @see AdminDao#findByPage(Page, AdminBean)
	 */
	public List<Admin> findByPage(Page<Admin> page,
			AdminBean bean) {
		QueryCondition qc = assembly(bean);
		qc.setMaxResults(page.getPageSize());
		qc.setOffset(page.getOffset());
		return findByQc(qc);
	}
	// 业务查询主要逻辑代码
	private void transNameQuery(AdminBean bean,QueryCondition qc){
		if(bean!=null){
			if(StringUtils.isNotBlank(bean.getKeyword())){
				qc.append(" And ( 1!=1 ");
				String[] keyword1=bean.getKeyword().split(" ");
				for(String str:keyword1){
					if(StringUtils.isNotBlank(str)){
						qc.add(" or obj.loginName like ? ", "%"+str.trim()+"%");
						qc.add(" or obj.realName like ? ", "%"+str.trim()+"%");
						qc.add(" or obj.nickName like ? ","%"+str.trim()+"%");
					}
				}
				qc.append(" )");
			}
			if(bean.getRole()!=null&&StringUtils.isNotBlank(bean.getRole().getRoleId())
					&&!bean.getRole().getRoleId().equals("0")){
				qc.add(" And obj.role.roleId = ? ", bean.getRole().getRoleId());
			}
			if(bean.getCreateTimeStart()!=null){
				qc.add("And obj.createTime >=? ", bean.getCreateTimeStart());
			}
			if(bean.getCreateTimeEnd()!=null){
				qc.add("And obj.createTime <=? ", bean.getCreateTimeEnd());
			}
			
			if(StringUtils.isNotBlank(bean.getLoginName())){
				qc.add("And obj.loginName = ? ", bean.getLoginName());
			}
            if(StringUtils.isNotBlank(bean.getRealName())){
				qc.add("And obj.realName like ? ", "%"+bean.getRealName()+"%");
			}
            if(StringUtils.isNotBlank(bean.getNickName() )){
				qc.add("And obj.nickName like ? ","%"+ bean.getNickName()+"%");
			}
            if(bean.getActiveStatus() != null){
				qc.add("And obj.activeStatus = ? ", bean.getActiveStatus());
			}
            if(StringUtils.isNotBlank(bean.getMemo())){
				qc.add("And obj.memo like ? ", "%"+bean.getMemo()+"%");
			}
            if(StringUtils.isNotBlank(bean.getEmail())){
				qc.add("And obj.email like ? ", "%"+bean.getEmail()+"%");
			}
            if(StringUtils.isNotBlank(bean.getMobile())){
				qc.add("And obj.mobile like ? ", "%"+bean.getMobile()+"%");
			}
            if(StringUtils.isNotBlank(bean.getTelephone())){
				qc.add("And obj.telephone like ? ", "%"+bean.getTelephone()+"%");
			}
            if(StringUtils.isNotBlank(bean.getLastSuccessIp())){
				qc.add("And obj.lastSuccessIp = ? ", bean.getLastSuccessIp());
			}
            if(bean.getLastSuccessTime() != null){
				qc.add("And obj.lastSuccessTime = ? ", bean.getLastSuccessTime());
			}
            if(StringUtils.isNotBlank(bean.getLastFailIp())){
				qc.add("And obj.lastFailIp = ? ", "%"+bean.getLastFailIp()+"%");
			}
            if(bean.getLastFailTime() != null){
				qc.add("And obj.lastFailTime = ? ", bean.getLastFailTime());
			}
            if(bean.getFailNum() != null){
				qc.add("And obj.failNum = ? ", bean.getFailNum());
			}
            if(bean.getCreateTime() != null){
				qc.add("And obj.createTime = ? ", bean.getCreateTime());
			}
            if(StringUtils.isNotBlank(bean.getCreateLoginName())){
				qc.add("And obj.createLoginName = ? ", bean.getCreateLoginName());
			}
            if(StringUtils.isNotBlank(bean.getCreateRealName())){
				qc.add("And obj.createRealName like ? ", "%"+bean.getCreateRealName()+"%");
			}
            if(StringUtils.isNotBlank(bean.getUpdateLoginName())){
				qc.add("And obj.updateLoginName like ? ", "%"+bean.getUpdateLoginName()+"%");
			}
            if(StringUtils.isNotBlank(bean.getUpdateRealName() )){
				qc.add("And obj.updateRealName like ? ", "%"+bean.getUpdateRealName()+"%");
			}
            qc.add("And obj.adminId <> ?", DBInitId.CMS_SUPPER_ADMIN_ID);
            qc.appenOrderBy(" obj.activeStatus desc,obj.updateTime desc, obj.createTime desc,obj.id desc ");
		}
	}

	public boolean checkNameUnique(AdminBean adminBean,String adminId){
		boolean unique=false;
		List<Admin> adminList1=null;
		List<Admin> adminList2=null;
		QueryCondition qc1 = new QueryCondition(MAIN_HQL);
		if((null!=adminBean)&& StringUtils.isNotBlank(adminBean.getLoginName())){
			qc1.add("And obj.loginName =? ", adminBean.getLoginName());
			adminList1=findByQc(qc1);
		}

		QueryCondition qc2 = new QueryCondition(MAIN_HQL);
		if((null!=adminBean)&& StringUtils.isNotBlank(adminBean.getNickName())){
			qc2.add("And  obj.nickName =?", adminBean.getNickName());
			adminList2=findByQc(qc2);
		}
		if(StringUtils.isNotBlank(adminId)){
			if(null!=adminList1&&!adminList1.isEmpty()){
				if(!adminList1.get(0).getAdminId().equals(adminId)){
					unique=true;
				}
			}
			if((null!=adminList2)&&!adminList2.isEmpty()){
				if(!adminList2.get(0).getAdminId().equals(adminId)){
					unique=true;
				}
			}
		}else{
			if((null!=adminList1)&&!adminList1.isEmpty()){
				unique=true;
			}
			if((null!=adminList2)&&!adminList2.isEmpty()){
				unique=true;
			}
		}
		return unique;
	}
	/**
	 * 登录名、密码查询admin
	 * 登陆验证身份
	 * @author hasau
	 */ 
	@SuppressWarnings("unchecked")
	public Admin getLoginAdmin(String loginName) {
		LOGGER.debug("开始查询 user:{}",loginName);
		assert(loginName!=null);
////		LOGGER.debug("MAIN user:{}",loginName);
//		QueryCondition qc = new QueryCondition(MAIN_HQL);
//		CLOGGER.debug("QC add:{}",loginName);
//		qc.add("And obj.loginName = ? ", loginName);
////		LOGGER.debug("start findByQc:{}",loginName);
		List<Admin> list = this.getHibernateTemplate().find("From Admin as obj where obj.loginName = ?", loginName);
		LOGGER.debug("结束查询 user:{}",loginName);
		if(list.isEmpty()) return null;
		return list.get(0);
		 
	}
	
	@SuppressWarnings("unchecked")
	public List<Admin> getAdminsByOper(String operTargetId,String operTargetType,String operCode){
		QueryCondition hql= new QueryCondition("From Admin a ");
		hql.append(" and a.id in(select aor.admin.id from AdminOperRela as aor where 1=1 ");
		if(StringUtils.isNotBlank(operTargetId)){
			hql.append(" and aor.operTargetId like '%"+operTargetId+"%'");
		}
		if(StringUtils.isNotBlank(operTargetType)){
			hql.append(" and aor.operTargetType='"+operTargetType+"'");
		}
		if(StringUtils.isNotBlank(operCode)){
			hql.append(" and aor.operCode.operCode='"+operCode+"'");
		}
		hql.append(" ) or exists ( from RoleOperRela as ror where  1=1 ");
		if(StringUtils.isNotBlank(operTargetId)){
			hql.append(" and ror.operTargetId like '%"+operTargetId+"%'");
		}
		if(StringUtils.isNotBlank(operTargetType)){
			hql.append(" and ror.operTargetType='"+operTargetType+"' ");
		}
		if(StringUtils.isNotBlank(operCode)){
			hql.append(" and ror.operCode.operCode='"+operCode+"'");
		}
		hql.append(" and a in elements(ror.role.admins))");
		List<?> list = find(hql);
		return (List<Admin>) list;
	}

	public List<Admin> getAllUsableAdmins() {
		QueryCondition qc = new QueryCondition(MAIN_HQL);
		qc.append(" And obj.activeStatus = 1");
		return findByQc(qc);
	} 
	
	public List<Admin>  getAdminsBynames(String loginNames){
		if(StringUtils.isBlank(loginNames)) return new ArrayList<Admin>();
		QueryCondition qc = new QueryCondition(MAIN_HQL);
		String[] ns = loginNames.split(",");
		qc.append(" And (  ");
		int i=1;
		for(String n : ns){
			qc.add(" obj.loginName  =  ? ", n.trim());
			
			if(i != ns.length) qc.append(" or ");
			i++;
		}
		qc.append(" ) ");
		 
		return findByQc(qc);
	}

	public List<Admin> findUsableAdminByRoleId(String roleId) {
		QueryCondition qc = new QueryCondition(MAIN_HQL);
		qc.add("And obj.role.roleId = ? ", roleId);
		qc.add("And obj.activeStatus != ? ", new Boolean(false));
		return findByQc(qc);
	}	
}